package com.example.rentsystem.servlet.api;

import com.example.rentsystem.entity.Advice;
import com.example.rentsystem.entity.User;
import com.example.rentsystem.service.AdviceService;
import com.example.rentsystem.service.impl.AdviceServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Date;

@WebServlet("/add-advice")
public class AddAdviceServlet extends HttpServlet {

    AdviceService service;

    @Override
    public void init() throws ServletException {
        service = new AdviceServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("login-first", true);
            resp.sendRedirect("login");
            return;
        }
        String content = req.getParameter("content");
        if (content.length() > 50) {
            session.setAttribute("advice", "");
            resp.sendRedirect("advice");
            return;
        }
        service.addAdvice(Advice.builder()
                .content(content)
                .time(new Date())
                .build());
        resp.sendRedirect("advice");
    }
}
